import Vue from 'vue';
import Vuex from 'vuex';
import storage from '../utils/storage';
import userModel from '../api/user.js';
import router from '../router/index';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userInfo: storage.getItem('userInfo') || '',
    menuList: storage.getItem('menuList') || [],
    actionList: storage.getItem('actionList') || [],
  },
  mutations: {
    // 存储用户信息
    setUserInfo(state, info) {
      state.userInfo = info;
      storage.setItem('userInfo', info);
    },
    // 存储菜单数据
    saveMenuList(state, menuList) {
      state.menuList = menuList;
      storage.setItem('menuList', menuList);
    },
    // 存储按钮权限
    saveactionList(state, actionList) {
      state.actionList = actionList;
      storage.setItem('actionList', actionList);
    },
  },
  getters: {
    // 用户信息
    getUserInfo(state) {
      return state.userInfo;
    },
  },
  actions: {
    // 登录方法
    handleUserLogin({ commit }, loginform) {
      return new Promise(async (resolve, reject) => {
        try {
          const result = await userModel.userLogin(loginform);
          // 把用户名字存起来
          commit('setUserInfo', result);
          resolve(result);
        } catch (err) {
          reject(err);
        }
      });
    },
    // 退出登录方法
    handlelogout({ commit }) {
      commit('setUserInfo', '');
      router.push('/login');
    },
  },
  modules: {
  },
});
